import React, { ReactElement, useEffect } from 'react';
import { BackHandler } from 'react-native';
import { NavigationScreenProps } from 'react-navigation';

import Notch, { NotchType } from '../../components/Notch';
import Provider from './reducer';

import styles from './style';
import Container from './components/Container';
import {
  clearVerifyInterval,
  handleBackButton,
  setIsBind,
  setShowAgreement
} from './actions';
import tracker from '../../util/actionTracker';
import { showLogin } from '../../constant/events';
import { isIOS } from '../../constant';
import { systemUtil } from '../../util/native';
import { getHasShowAgreement } from '../../store/common';

export default (props: NavigationScreenProps): ReactElement => {
  const { navigation } = props;
  const isBind = navigation.getParam('isBind') || false;

  useEffect((): (() => void) => {
    setIsBind(isBind);

    if (isIOS) {
      systemUtil.getIDFA().then((res): void => {
        tracker.reportAction(showLogin, {
          data: res
        });
      });
    } else {
      tracker.reportAction(showLogin, {
        data: systemUtil.getIMEI()
      });
    }

    BackHandler.addEventListener('hardwareBackPress', handleBackButton);

    const hasShowAgreement = getHasShowAgreement();
    if (!hasShowAgreement) {
      setShowAgreement(true);
    }

    return (): void => {
      clearVerifyInterval();
      BackHandler.removeEventListener('hardwareBackPress', handleBackButton);
    };
  }, [isBind, navigation]);
  return (
    <Provider>
      <Notch type={NotchType.Top} style={styles.container}>
        <Container />
      </Notch>
    </Provider>
  );
};
